<template>
  <div style="margin-top: 2vh">
    <div style="background-color: white; width: 68vw; margin: auto;">
      <!-- 上方标题 -->
      <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; width: 100%;">
        <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw;">编辑纵向课题</span>
        <span style="font-size: 0.8rem; color: #8c8c8c; margin-left: 1vw; line-height: 7vh;">请编辑您的纵向课题的</span>
        <span style="color: #8c8c8c; line-height: 7vh; font-size: 0.8rem; font-weight: bold;">相关文件：立项书、任务书等。</span>
      </div>

      <pdf-preview
          ref="pdfPreviewRef"
          :pdf-url="ruleForm.pdfPath"
          @update:pdf-path="updatePdfPath"
          @rotations-changed="handleRotationsChanged"
      ></pdf-preview>
    </div>

    <!-- 填写信息 -->
    <div style="background-color: white; width: 68vw; margin: auto; display: flex; flex-direction: column; padding-bottom: 5vh; margin-top: 3vh;margin-bottom: 3vh ">
      <div style="flex: 1;">
        <div style="border-bottom: 1px solid #e9e9e9; height: 7vh; display: flex;">
          <span style="font-weight: bold; font-size: 1.1rem; line-height: 7vh; margin-left: 1.5vw">编辑信息</span>
          <span style="line-height: 7vh; margin-left: 3vh; color: #CACACA; font-weight: bold">带<span style="color: red;"> * </span>号为必填项</span>
        </div>

        <div>
          <el-form :model="ruleForm" :rules="rules" ref="ruleFormRef" label-width="120px" style="margin-top: 5vh">
            <el-form-item label="课题名称" prop="projectName" required>
              <el-input v-model="ruleForm.projectName" placeholder="请填写课题名称" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="基金名称" prop="fundName" required>
              <el-input v-model="ruleForm.fundName" placeholder="如：国家自然科学基金" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="课题类型" prop="projectType">
              <el-select v-model="ruleForm.projectType" placeholder="请选择课题类型" style="width: 34vw;">
                <el-option label="---请选择---" value=""></el-option>
                <el-option label="重点" value="重点"></el-option>
                <el-option label="面上" value="面上"></el-option>
                <el-option label="青年" value="青年"></el-option>
                <el-option label="一般" value="一般"></el-option>
                <el-option label="自筹" value="自筹"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="授予单位" prop="grantingUnit">
              <el-input v-model="ruleForm.grantingUnit" placeholder="请填写授予单位" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="课题级别" prop="projectLevel" required>
              <el-select v-model="ruleForm.projectLevel" placeholder="请选择课题级别" style="width: 34vw;">
                <el-option label="国家级" value="国家级"></el-option>
                <el-option label="省部级" value="省部级"></el-option>
                <el-option label="市厅级" value="市厅级"></el-option>
                <el-option label="校级" value="校级"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="课题编号" prop="projectNumber" >
              <el-input v-model="ruleForm.projectNumber" placeholder="请填写课题编号" style="width: 34vw;"></el-input>
            </el-form-item>

            <el-form-item label="到账经费(万)" prop="fundingAmount" >
              <el-input-number
                  v-model="ruleForm.fundingAmount"
                  :precision="2"
                  :step="0.1"
                  :min="0"
                  style="width: 34vw;"
                  placeholder="请输入到账经费金额">
              </el-input-number>
            </el-form-item>

            <el-form-item label="本人排名" prop="rank" required>
              <el-select v-model="ruleForm.rank" placeholder="请选择排名" style="width: 34vw;">
                <el-option
                    v-for="i in 13"
                    :key="i"
                    :label="`第${i}名`"
                    :value="i">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="开始时间" prop="startTime" required>
              <el-date-picker
                  v-model="ruleForm.startTime"
                  type="date"
                  placeholder="选择开始日期"
                  style="width: 34vw;"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="结束时间" prop="endTime" required>
              <el-date-picker
                  v-model="ruleForm.endTime"
                  type="date"
                  placeholder="选择结束日期"
                  style="width: 34vw;"
                  value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="课题状态" prop="projectStatus" required>
              <el-select v-model="ruleForm.projectStatus" placeholder="请选择课题状态" style="width: 34vw;">
                <el-option label="在研" value="在研"></el-option>
                <el-option label="结题" value="结题"></el-option>

              </el-select>
            </el-form-item>

            <el-form-item label="作者信息" prop="authorInfo">
              <div style="background-color: #f9f9f9; width: 55vw; height: auto; padding: 10px; border-radius: 4px;">
                <!-- 表头 -->
                <div style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #e8e8e8;">
                  <div style="width: 60px; text-align: center;">排序</div>
                  <div style="width: 120px; margin-left: 15px;">姓名</div>
                  <div style="width: 120px; margin-left: 15px;">作者身份</div>
                  <div style="flex: 1; margin-left: 15px;">单位名称</div>
                  <div style="width: 80px; margin-left: 15px;">操作</div>
                </div>

                <!-- 作者列表 -->
                <div v-for="(author, index) in ruleForm.authorInfo" :key="index"
                     style="display: flex; align-items: center; padding: 8px 0; border-bottom: 1px solid #f0f0f0;">
                  <el-select v-model="author.rank" style="width: 60px;">
                    <el-option
                        v-for="i in 13"
                        :key="i"
                        :label="i"
                        :value="i">
                    </el-option>
                  </el-select>

                  <el-input v-model="author.name" style="width: 120px; margin-left: 15px;" placeholder="姓名"></el-input>

                  <el-select v-model="author.identity" style="width: 120px; margin-left: 15px;" placeholder="身份">
                    <el-option
                        v-for="item in identityOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                  </el-select>

                  <el-select v-model="author.institution" placeholder="请选择单位名称" style="flex: 1; margin-left: 15px;">
                    <el-option label="信息工程学院" value="信息工程学院"></el-option>
                  </el-select>

                  <el-button
                      type="danger"
                      size="small"
                      @click="removeAuthor(index)"
                      style="width: 80px; margin-left: 15px;">
                    删除
                  </el-button>
                </div>

                <el-button @click="addAuthor" style="margin-top: 10px;">添加作者</el-button>
              </div>
            </el-form-item>

            <el-form-item label="备注信息" prop="remarks">
              <el-input
                  type="textarea"
                  :rows="4"
                  v-model="ruleForm.remarks"
                  placeholder="请输入备注信息"
                  style="width: 34vw;">
              </el-input>
            </el-form-item>
          </el-form>

          <div style="display: flex; justify-content: center; margin-top: 2vh">
            <button @click="submit" class="submit-button" :disabled="isSubmitting">
              {{ isSubmitting ? '更新中...' : '更 新' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import PdfPreview from "@/components/PdfPreview.vue"
import { getLongitudinalById, updateLongitudinal } from "@/api/Research/Longitudinal.js"
import { batchUpdatePdfPages } from "@/api/Manage/File.js";

const router = useRouter()
const route = useRoute()
const ruleFormRef = ref(null)
const pdfPreviewRef = ref(null)
const isSubmitting = ref(false) // 提交状态
const hasRotations = ref(false) // 是否有旋转
const currentRotations = ref([]) // 存储当前的旋转信息

const ruleForm = reactive({
  id: '',
  projectName: '',
  fundName: '',
  projectType: '',
  grantingUnit: '',
  projectLevel: '',
  projectNumber: '',
  fundingAmount: null,
  rank: null,
  startTime: '',
  endTime: '',
  projectStatus: '',
  remarks: '',
  pdfPath: '',
  authorInfo: [{
    rank: 1,
    name: '',
    identity: '',
    institution: ''
  }]
})

const identityOptions = [
  { value: '老师', label: '老师' },
  { value: '博士生', label: '博士生' },
  { value: '硕士生', label: '硕士生' },
  { value: '本科生', label: '本科生' },
  { value: '其他', label: '其他' }
]

const rules = reactive({
  projectName: [{ required: true, message: '请输入课题名称', trigger: 'blur' }],
  fundName: [{ required: true, message: '请输入基金名称', trigger: 'blur' }],
  projectLevel: [{ required: true, message: '请选择课题级别', trigger: 'change' }],
  rank: [{ required: true, message: '请选择本人排名', trigger: 'change' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
})

const addAuthor = () => {
  ruleForm.authorInfo.push({
    rank: ruleForm.authorInfo.length + 1,
    name: '',
    identity: '',
    institution: ''
  })
}

const removeAuthor = (index) => {
  ruleForm.authorInfo.splice(index, 1)
}

const updatePdfPath = (newPath) => {
  ruleForm.pdfPath = newPath.firstImageUrl
}

// 处理旋转状态变化
const handleRotationsChanged = (rotations) => {
  hasRotations.value = rotations.length > 0
  currentRotations.value = rotations
  console.log('旋转状态变化:', rotations)
}

const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

const submit = async () => {
  if (!ruleFormRef.value) return

  try {
    isSubmitting.value = true
    await ruleFormRef.value.validate()

    // 如果有旋转，先保存旋转
    if (hasRotations.value && currentRotations.value.length > 0) {
      try {
        // 组装批量更新请求数据
        const batchData = {
          filePath: ruleForm.pdfPath, // PDF文件路径
          pages: currentRotations.value.map(rotation => ({
            pageNumber: rotation.pageIndex + 1, // 页码从1开始
            rotation: rotation.rotation // 旋转角度
          }))
        }

        console.log('批量更新旋转请求数据:', batchData)

        const rotationResult = await batchUpdatePdfPages(batchData)
        console.log('批量更新旋转结果:', rotationResult)

        if (rotationResult.code !== "0") {
          ElMessage.error('保存旋转失败: ' + (rotationResult.message || '未知错误'))
          return
        }

        ElMessage.success('旋转保存成功')

        // 重置旋转状态
        hasRotations.value = false
        currentRotations.value = []

        // 通知PDF预览组件重新加载
        if (pdfPreviewRef.value && pdfPreviewRef.value.reloadPDF) {
          await pdfPreviewRef.value.reloadPDF(ruleForm.pdfPath)
        }

      } catch (rotationError) {
        console.error('保存旋转失败:', rotationError)
        ElMessage.error('保存旋转失败: ' + (rotationError.message || '网络错误'))
        return
      }
    }

    // 转换日期格式为时间戳
    const formData = {
      ...ruleForm,
      startTime: new Date(ruleForm.startTime).getTime(),
      endTime: new Date(ruleForm.endTime).getTime(),
      authorInfo: JSON.stringify(ruleForm.authorInfo)
    }

    const res = await updateLongitudinal(formData)
    if (res.code === 1) {
      ElMessage.success('更新成功')
      router.push("/main/research/Longitudinal")
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新错误:', error)
    ElMessage.error('表单验证失败，请检查必填项')
  } finally {
    isSubmitting.value = false
  }
}

onMounted(async () => {
  const longitudinalId = route.query.id
  if (longitudinalId) {
    try {
      const res = await getLongitudinalById(longitudinalId)
      if (res.code === 1 && res.data) {
        // 处理日期格式
        const data = {
          ...res.data,
          startTime: formatDate(res.data.startTime),
          endTime: formatDate(res.data.endTime),
          authorInfo: res.data.authorInfo ? JSON.parse(res.data.authorInfo) : []
        }
        Object.assign(ruleForm, data)
      } else {
        ElMessage.error('获取纵向课题信息失败')
      }
    } catch (error) {
      console.error('获取纵向课题信息出错:', error)
      ElMessage.error('获取纵向课题信息失败，请重试')
    }
  }
})
</script>

<style scoped>
.submit-button {
  color: white;
  height: 3.8vh;
  width: 10vw;
  background-color: #00b38a;
  cursor: pointer;
  border: none;
  border-radius: 4px;
}

.submit-button:hover:not(:disabled) {
  background-color: #009b77;
}

.submit-button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-select .el-input__inner) {
  text-align: left;
}
</style>
